<template>
  <el-input
    type="textarea"
    :value="valueString"
    @input="handleInput"
    :maxlength="maxlength"
    v-bind="$attrs"
  ></el-input>
</template>

<script>
export default {
  name: "ObjectInput",
  inheritAttrs: true,
  props: {
    value: {
      type: [Object, Array]
    },
    maxlength: {
      type: Number,
      default: 9999
    }
  },
  data() {
    return { valueString: "{}" };
  },
  computed: {
    valueObject() {
      return this.parseObject(this.valueString);
    }
  },
  created() {
    this.valueString = JSON.stringify(this.value);
  },
  methods: {
    parseObject(valueString) {
      try {
        return JSON.parse(valueString);
      } catch (e) {
        return {};
      }
    },
    handleBlur() {
      this.$emit("input", this.valueObject);
    },
    handleInput(valueString) {
      let valueObject = this.parseObject(valueString);
      let length = Object.keys(valueObject).length;
      if (length > 0) {
        this.$emit("input", valueObject);
      }
      this.valueString = valueString;
    }
  },
  watch: {
    value(newValue) {
      this.valueString = JSON.stringify(newValue);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>
